<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 掌萌人
-->
<template>
  <div>
    <van-form class="zhang-meng">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.Mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.PassWord"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 抢单间隔 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <!-- 任务类型 -->
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.AccountName">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import {
  getLogin,
  getSysSendTaskAccount,
  getNewsSystemSendTask,
  getQueryTaskReceivingStatus,
  clientId,
  clientSecret,
  ajaxFun
} from "@/api/zhang-meng";
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "ZhangMeng",
  props: {
    // index
    index: {
      type: String,
      default: ""
    },
    // icon
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 账号密码
      ruleForm: {
        Mobile: "",
        PassWord: "",
        client_id: clientId,
        client_secret: clientSecret
      },
      // 间隔时间
      IntervalTime: 12,
      // 任务类型
      type: 1,
      typeOptions: [
        {
          label: "垫付任务",
          type: 1
        },
        {
          label: "浏览任务",
          type: 2
        }
      ],
      // 标记
      startFlag: false,
      // 接口提示
      returnContent: [],
      // 账号弹窗
      show: false,
      // 账号列表
      accountList: [],
      // 返回参数
      Token: "",
      UserId: "",
      AccountId: "",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: "",
      timer: null
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 44 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 提示
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 索引
    index() {
      if (this.item.index === 44 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.Mobile = this.item.user;
        this.ruleForm.PassWord = this.item.pass;
        this.type = this.item.type || 1;

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 44 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.Mobile = this.item.user;
      this.ruleForm.PassWord = this.item.pass;
      this.type = this.item.type || 1;
    }
  },
  methods: {
    // 开始接单
    onStart() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        this.isAcceptSuc = false;
        // 登录
        this.returnContent.unshift(alertMsg("正在登录"));
        this.onLogin(_this);
      } else {
        this.startFlag = false;
        this.returnContent.unshift(alertMsg("接单取消"));
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 登录
    onLogin(_this) {
      let param = {
        type: "post",
        data: _this.ruleForm
      };
      ajaxFun(getLogin, param, res => {
        if (res) {
          _this.returnContent.unshift(alertMsg(res.msg));
          if (res.errcode === 1) {
            _this.startFlag = false;
          } else {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.Mobile,
              pass: _this.ruleForm.PassWord,
              type: _this.type,
              index: _this.index
            });
            _this.UserId = res.obj.UserId;
            _this.Token = res.obj.Token;
            // 获取账号信息
            _this.onGetSysSendTaskAccount(_this);
          }
        } else {
          // 登录异常 => 重新登录
          _this.onLogin(_this);
        }
      });
    },
    // 获取账号信息
    onGetSysSendTaskAccount(_this) {
      _this.accountList = [];
      let param = {
        type: "post",
        data: {
          UserId: _this.UserId,
          Token: _this.Token
        }
      };
      ajaxFun(getSysSendTaskAccount, param, res => {
        if (res.errcode === 1) {
          _this.startFlag = false;
        } else {
          _this.accountList = res.obj;
          if (_this.accountList.length === 1) {
            _this.onChange(_this.accountList[0]);
          } else {
            _this.show = true;
          }
        }
      });
    },
    // 选择账号
    onChange(list) {
      const _this = this;
      this.show = false;
      this.returnContent.unshift(
        alertMsg("接单号: " + list.AccountName + " 即将开始接单，请耐心等待...")
      );
      let param = {
        type: "post",
        data: {
          UserId: _this.UserId,
          Token: _this.Token,
          AccountIdList: list.IsBind + ",",
          PlatIdList: list.PlatId + ",",
          TaskType: _this.type,
          VersionControl: "1.0.27",
          MaxAdvancePayMoney: 500
        }
      };
      ajaxFun(getNewsSystemSendTask, param, res => {
        if (res.errcode === 3) {
          _this.returnContent.unshift(alertMsg(res.msg));
          _this.startFlag = false;
        } else {
          _this.onGetQueryTaskReceivingStatus(_this);
        }
      });
    },
    // 获取任务
    onGetQueryTaskReceivingStatus(_this) {
      clearInterval(_this.timer);
      _this.returnContent.unshift(alertMsg("暂无合适的任务，继续接单..."));
      let param = {
        type: "post",
        data: {
          UserId: _this.UserId,
          Token: _this.Token
        }
      };
      ajaxFun(getQueryTaskReceivingStatus, param, res => {
        if (res) {
          if (res.errcode === 0 && res.obj.TaskFlag == 0) {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetQueryTaskReceivingStatus(_this);
              }
            }, _this.IntervalTime * 1000);
          } else {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          }
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetQueryTaskReceivingStatus(_this);
            }
          }, _this.IntervalTime * 1000);
        }
      });
    }
  }
};
</script>
